package com.shenmawl.common.utils.mqtt;

import com.shenmawl.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("spring.mqtt")
public class MqttConfig {
    @Autowired
    private MqttPushClient mqttPushClient;

    private String username;
    private String password;
    private String hostUrl;
    private String clientId;
    private String defaultTopic;
    private int timeout;
    private int keepalive;
    private boolean enabled;

    // Getters and Setters

    @Bean
    public MqttPushClient getMqttPushClient() {
        if(enabled) {
            String[] mqtt_topic = StringUtils.split(defaultTopic, ",");
            mqttPushClient.connect(hostUrl, clientId, username, password, timeout, keepalive);
            for(String topic : mqtt_topic) {
                mqttPushClient.subscribe(topic, 0);
            }
        }
        return mqttPushClient;
    }
}
